package org.syncsoft.overalt.domain.community.json;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.syncsoft.overalt.common.json.AbstractJsonConverter;
import org.syncsoft.overalt.common.json.JSonTree;
import org.syncsoft.overalt.domain.community.entity.Community;
import org.syncsoft.overalt.domain.user.entity.User;

/**
 * JSON converter to Community entity
 * @author tptfc
 *
 */
public class CommunitiesJsonConverter extends AbstractJsonConverter<Collection<Community>> {

	/*
	 * (non-Javadoc)
	 * @see org.syncsoft.overalt.common.json.AbstractJsonConverter#converter(org.syncsoft.overalt.common.json.JSonTree)
	 */
	@Override
	protected Collection<Community> converter(JSonTree jsonTree) {
		Collection<Community> communities = null;
		
		if (jsonTree != null) {
			communities = extractMembers(jsonTree);
		}
		
		return communities;
	}

	/**
	 * 
	 * @param jsonTree
	 * @return
	 */
	private Collection<Community> extractMembers(JSonTree jsonTree) {
		Collection<Community> communities = new ArrayList<Community>();
		List<JSonTree> communitiesEntities = jsonTree.getJsonTreesFronEntityName("entities");
		
		for (JSonTree entity : communitiesEntities) {
			Community community = new Community();
			
			
			populeEntity(community, entity);
			
			JSonTree userEntity = entity.getJsonTreeFronEntityName("owner");
			if (userEntity != null) {
				User owner = new User();
				populeEntity(owner, userEntity);
				community.setOwner(owner);
			}
			
			communities.add(community);
		}
		
		return communities;
	}

}
